package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.CommonCommentComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.jersey.api.EasemobMessages;
import com.dy.lock.screen.pojo.CommonCommentInfo;
import com.dy.lock.screen.pojo.CustomerBlacklistInfo;
import com.dy.lock.screen.pojo.CustomerMarkInfo;
import com.dy.lock.screen.pojo.MaterialCommentInfo;
import com.dy.lock.screen.pojo.UserInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.CommonCommentService;
import com.dy.lock.screen.service.CustomerBlacklistService;
import com.dy.lock.screen.service.CustomerMarkRelationService;
import com.dy.lock.screen.service.MaterialCommentService;
import com.dy.lock.screen.service.UserService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.CommonCommentVo;
import com.dy.lock.screen.vo.EasemobVo;
import com.google.gson.Gson;

@Component("commonCommentComponent")
public class CommonCommentComponentImpl implements CommonCommentComponent {

	private static final Logger log = Logger
			.getLogger(CommonCommentComponentImpl.class);
	private Gson gson;

	@Resource(name = "commonCommentService")
	private CommonCommentService commonCommentService;
	@Resource(name = "materialCommentService")
	private MaterialCommentService materialCommentService;
	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "customerBlacklistService")
	private CustomerBlacklistService customerBlacklistService;
	@Resource(name = "customerMarkRelationService")
	private CustomerMarkRelationService customerMarkRelationService;

	// @Resource(name = "customerAttentionService")
	// private CustomerAttentionService customerAttentionService;

	public CommonCommentComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean delete(String body, Head head) {
		CommonCommentVo vo = gson.fromJson(body, CommonCommentVo.class);
		if (vo != null) {
			CommonCommentInfo commInfo = new CommonCommentInfo();
			commInfo.setCommonCommentId(vo.getCommonCommentId());
			commInfo.setIsDelete(Constant.IS_DELETE);
			CommonCommentInfo ccInfo = this.commonCommentService
					.queryByPrimaryKey(vo.getCommonCommentId());
			MaterialCommentInfo macInfo = null;
			if (ccInfo != null) {
				macInfo = this.materialCommentService.queryByPrimaryKey(ccInfo
						.getCommentId());
			}
			if ((ccInfo != null && vo.getUserId().equals(ccInfo.getUserId()))
					|| (macInfo != null && vo.getUserId().equals(
							macInfo.getUserId()))) {
				int result = this.commonCommentService.falseDelete(commInfo);
				if (result >= 0) {
					return true;
				} else {
					throw new ServerDisponseException(
							TransmissionCode.OPERATOR_EXCEPTION.getCode(),
							TransmissionCode.OPERATOR_EXCEPTION.getMessage());
				}
			} else {
				throw new ServerDisponseException(
						TransmissionCode.DO_NOT_DELETE_OTHER_USER_COMMON_COMMENT
								.getCode(),
						TransmissionCode.DO_NOT_DELETE_OTHER_USER_COMMON_COMMENT
								.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",用户删除普通评论操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

	@Override
	public List<CommonCommentInfo> list(String body, Head head) {
		CommonCommentVo vo = gson.fromJson(body, CommonCommentVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> para = new HashMap<String, Object>();
			para.put("pageStart", pageStart);
			para.put("pageEnd", pageEnd);
			para.put("isDelete", Constant.IS_NOT_DELETE);
			if (StringUtils.isNotBlank(vo.getCommentId())) {
				para.put("commentId", vo.getCommentId());
			}

			List<CommonCommentInfo> commonCommentList = this.commonCommentService
					.queryPage(para);
			if (commonCommentList != null && !commonCommentList.isEmpty()) {
				for (CommonCommentInfo cInfo : commonCommentList) {
					String userId = cInfo.getUserId();
					UserInfo userInfo = this.userService.queryByUserId(userId,
							head);
					String username = userInfo.getUserName();
					if (StringUtils.isNotBlank(username)) {
						cInfo.setUserName(username);
					} else {
						cInfo.setUserName(userId);
					}
					if (StringUtils.isNoneBlank(cInfo.getHeaderPath())) {
						cInfo.setHeaderPath(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ cInfo.getHeaderPath());
					}
					cInfo.setCommentPicPath(CommonUtil.splitToString(cInfo
							.getCommentPicPath(), ";"));
					if (StringUtils.isNotBlank(vo.getCommentId())) {
						String atIds = cInfo.getHaveAt();
						List<UserInfo> userList = CommonUtil
								.getUserListByUserIds(userService, atIds);
						cInfo.setAtUserList(userList);
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(cInfo.getUserId());
					cInfo.setMarkInfoList(markInfos);
				}
			}
			return commonCommentList;
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取普通评论列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean uploadCommonComment(String body, Head head) {
		CommonCommentVo vo = gson.fromJson(body, CommonCommentVo.class);
		if (vo != null) {
			MaterialCommentInfo mater = this.materialCommentService
					.queryByPrimaryKey(vo.getCommentId());
			CustomerBlacklistInfo blacklistInfo = new CustomerBlacklistInfo();
			blacklistInfo.setBlackCustomer(mater.getUserId());
			blacklistInfo.setBeBlackedCustomer(vo.getUserId());
			CustomerBlacklistInfo bl = customerBlacklistService
					.queryByBlackIdAndBeBlackId(blacklistInfo);
			if (bl != null) {
				log.info("requestId:" + head.getRequestId()
						+ "当前用户已被此文章评论所有者加入黑名单，不能再对此用户的文章评论发表普通评论。");
				throw new ServerDisponseException(
						TransmissionCode.DO_NOT_ATTENTION_USER_BECAUSE_BLACK_USER
								.getCode(),
						TransmissionCode.DO_NOT_ATTENTION_USER_BECAUSE_BLACK_USER
								.getMessage());
			}
			CommonCommentInfo info = new CommonCommentInfo();
			info.setCommentId(vo.getCommentId());
			info.setCommonComment(vo.getCommonComment());
			info.setIsDelete(Constant.IS_NOT_DELETE);
			info.setUserId(vo.getUserId());
			info.setHaveAt(vo.getAtIds());
			String result = this.commonCommentService.save(info);
			if (StringUtils.isNotBlank(result)) {
				// CustomerAttentionInfo attInfo = new CustomerAttentionInfo();
				// attInfo.setBeConcernedId(vo.getUserId());
				// List<String> sendUserIds = this.customerAttentionService
				// .queryByAidOrBeid(attInfo);
				// 消息要发送的人
				List<String> sendUserIds = new ArrayList<String>();
				if (mater != null && !vo.getUserId().equals(mater.getUserId())) {
					String materialUserId = mater.getUserId();
					sendUserIds.add(materialUserId);

					UserInfo userInfo = this.userService.queryByUserId(vo
							.getUserId(), head);
					String username = userInfo.getUserName();
					if (StringUtils.isBlank(username)) {
						username = vo.getUserId();
					}
					EasemobVo easemobVo = new EasemobVo();
					// 谁发的消息
					easemobVo.setUserId(vo.getUserId());
					easemobVo.setUserName(username);
					easemobVo
							.setMessageType(Constant.MESSAGE_TYPE_COMMON_COMMENT);
					easemobVo.setCommonCommentOrLikeId(result);
					easemobVo.setMessageTime(new Date());
					List<String> failedUserId = EasemobMessages.sendMessages(vo
							.getUserId(), sendUserIds, gson.toJson(easemobVo));
					if (failedUserId != null && !failedUserId.isEmpty()) {
						log.info("requestId:" + head.getRequestId()
								+ ",上传普通评论时，发送消息的失败用户ID："
								+ failedUserId.toString());
					}
				}

				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",上传普通评论时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
